package com.stark.commons.spring.web.support.zuul;

import static org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer.Runner.customize;

import java.util.List;
import java.util.Optional;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.BasicHttpEntity;
import org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequest;
import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext;
import org.springframework.util.AntPathMatcher;

import com.stark.commons.spring.web.boot.properties.ZuulTimeoutProperties;
import com.stark.commons.spring.web.boot.properties.ZuulTimeoutProperties.RouteTimeout;
import com.stark.commons.spring.web.boot.properties.ZuulTimeoutProperties.UriTimeout;

/**
 * 扩展 {@link org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequest}，支持 uri 接口级别的超时配置。
 * 
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 * @see org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequest
 */
public class CustomRibbonApacheHttpRequest extends RibbonApacheHttpRequest {
	
	private final ZuulTimeoutProperties zuulTimeoutProperties;
	
	public CustomRibbonApacheHttpRequest(RibbonCommandContext context, ZuulTimeoutProperties zuulTimeoutProperties) {
		super(context);
		this.zuulTimeoutProperties = zuulTimeoutProperties;
	}
	
	@Override
	public HttpUriRequest toRequest(RequestConfig requestConfig) {
		final RequestBuilder builder = RequestBuilder.create(this.context.getMethod());
		builder.setUri(this.uri);
		for (final String name : this.context.getHeaders().keySet()) {
			final List<String> values = this.context.getHeaders().get(name);
			for (final String value : values) {
				builder.addHeader(name, value);
			}
		}

		for (final String name : this.context.getParams().keySet()) {
			final List<String> values = this.context.getParams().get(name);
			for (final String value : values) {
				builder.addParameter(name, value);
			}
		}

		if (this.context.getRequestEntity() != null) {
			final BasicHttpEntity entity;
			entity = new BasicHttpEntity();
			entity.setContent(this.context.getRequestEntity());
			// if the entity contentLength isn't set, transfer-encoding will be set
			// to chunked in org.apache.http.protocol.RequestContent. See gh-1042
			Long contentLength = this.context.getContentLength();
			if ("GET".equals(this.context.getMethod())
					&& (contentLength == null || contentLength < 0)) {
				entity.setContentLength(0);
			}
			else if (contentLength != null) {
				entity.setContentLength(contentLength);
			}
			builder.setEntity(entity);
		}

		customize(this.context.getRequestCustomizers(), builder);
		
		Optional<RouteTimeout> routeTimeout = zuulTimeoutProperties.getRouteTimeout()
			.stream()
			.filter(x -> x.getServiceId().equals(context.getServiceId()))
			.findFirst();
		UriTimeout uriTimeout = null;
		if (routeTimeout.isPresent()) {
			AntPathMatcher matcher = new AntPathMatcher();
			uriTimeout = routeTimeout.get().getUriTimeout()
				.stream()
				.filter(x -> matcher.match(x.getUri(), uri.getPath()) && x.getMethod().toString().equalsIgnoreCase(context.getMethod()))
				.findFirst()
				.orElse(null);
		}
		if (uriTimeout != null) {
			RequestConfig.Builder _builder = RequestConfig.copy(requestConfig);
			_builder.setConnectTimeout(uriTimeout.getConnectTimeout());
			_builder.setSocketTimeout(uriTimeout.getReadTimeout());
            builder.setConfig(_builder.build());
		} else {
			builder.setConfig(requestConfig);
		}
		return builder.build();
	}

}
